#!/usr/bin/env python3
"""调试MCP stdio通信"""

import json
import subprocess
import sys
import time
import os
from threading import Thread
import queue

def debug_mcp_stdio():
    """调试MCP stdio通信"""
    
    print("=== MCP Stdio 调试测试 ===")
    
    # 设置环境变量
    env = os.environ.copy()
    env['PYTHONPATH'] = 'd:\\MCP\\mcp2'
    
    try:
        # 启动MCP服务器进程
        print("启动MCP服务器...")
        process = subprocess.Popen(
            ['python', 'main.py', '--mode', 'stdio', '--config', 'config'],
            cwd='d:\\MCP\\mcp2',
            env=env,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=0
        )
        
        print(f"进程PID: {process.pid}")
        
        # 等待服务器启动
        time.sleep(3)
        
        # 检查进程状态
        if process.poll() is not None:
            stdout, stderr = process.communicate()
            print(f"服务器进程意外退出，退出码: {process.returncode}")
            print(f"标准输出: {stdout}")
            print(f"错误输出: {stderr}")
            return
        
        print("服务器正在运行")
        
        # 创建队列来收集输出
        stdout_queue = queue.Queue()
        stderr_queue = queue.Queue()
        
        def read_stdout():
            while True:
                try:
                    line = process.stdout.readline()
                    if line:
                        stdout_queue.put(('stdout', line.strip()))
                    else:
                        break
                except Exception as e:
                    stdout_queue.put(('error', f'stdout读取错误: {e}'))
                    break
        
        def read_stderr():
            while True:
                try:
                    line = process.stderr.readline()
                    if line:
                        stderr_queue.put(('stderr', line.strip()))
                    else:
                        break
                except Exception as e:
                    stderr_queue.put(('error', f'stderr读取错误: {e}'))
                    break
        
        # 启动读取线程
        stdout_thread = Thread(target=read_stdout, daemon=True)
        stderr_thread = Thread(target=read_stderr, daemon=True)
        stdout_thread.start()
        stderr_thread.start()
        
        # 发送初始化请求
        init_request = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "clientInfo": {
                    "name": "debug-client",
                    "version": "1.0.0"
                }
            }
        }
        
        message = json.dumps(init_request) + "\n"
        print(f"\n发送消息: {message.strip()}")
        
        try:
            process.stdin.write(message)
            process.stdin.flush()
            print("消息已发送到stdin")
        except Exception as e:
            print(f"发送消息失败: {e}")
            return
        
        # 监听输出
        print("\n等待响应...")
        start_time = time.time()
        timeout = 15
        
        while time.time() - start_time < timeout:
            # 检查stdout
            try:
                while True:
                    msg_type, content = stdout_queue.get_nowait()
                    print(f"[{msg_type}] {content}")
                    
                    # 检查是否是JSON响应
                    if content.startswith('{'):
                        try:
                            response = json.loads(content)
                            if 'result' in response:
                                print("\n✓ 收到有效的初始化响应!")
                                print(f"响应: {json.dumps(response, indent=2)}")
                                process.terminate()
                                return True
                        except json.JSONDecodeError:
                            pass
            except queue.Empty:
                pass
            
            # 检查stderr
            try:
                while True:
                    msg_type, content = stderr_queue.get_nowait()
                    print(f"[{msg_type}] {content}")
            except queue.Empty:
                pass
            
            time.sleep(0.1)
        
        print("\n✗ 响应超时")
        
        # 发送第二个测试消息
        print("\n尝试发送第二个消息...")
        tools_request = {
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list"
        }
        
        message2 = json.dumps(tools_request) + "\n"
        print(f"发送消息: {message2.strip()}")
        
        try:
            process.stdin.write(message2)
            process.stdin.flush()
        except Exception as e:
            print(f"发送第二个消息失败: {e}")
        
        # 再等待一段时间
        time.sleep(3)
        
        # 收集剩余输出
        print("\n收集剩余输出...")
        try:
            while True:
                msg_type, content = stdout_queue.get_nowait()
                print(f"[{msg_type}] {content}")
        except queue.Empty:
            pass
        
        try:
            while True:
                msg_type, content = stderr_queue.get_nowait()
                print(f"[{msg_type}] {content}")
        except queue.Empty:
            pass
        
    except Exception as e:
        print(f"调试过程中发生错误: {e}")
    
    finally:
        # 清理进程
        try:
            if process.poll() is None:
                process.terminate()
                process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            process.kill()
            process.wait()
        except Exception as e:
            print(f"清理进程时发生错误: {e}")
    
    return False

if __name__ == "__main__":
    success = debug_mcp_stdio()
    print(f"\n调试结果: {'成功' if success else '失败'}")